package com.ykht.proj.common.core.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import lombok.experimental.UtilityClass;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;

import java.util.Map;

/**
 * 经纬度计算距离的工具
 */
@UtilityClass
public class DistanceUtil {

	private String latitude = "latitude";
	private String longitude = "longitude";


	/*public static void main(String[] args) {
		System.out.println(getDistanceMeter(39.99773,116.478074,40.000383,116.487416,Ellipsoid.Sphere));
		System.out.println(getDistanceMeter(39.99773,116.478074,40.000383,116.487416));
		System.out.println(getDistanceMeter2Long(39.99773,116.478074,40.000383,116.487416));
	}*/

	/**
	 *
	 * @param lat 纬度
	 * @param lon 精度
	 * @param lat1
	 * @param lon1
	 * @param ellipsoid  计算方式
	 * @return
	 */
	public double getDistanceMeter(Double lat, Double lon,Double lat1, Double lon1, Ellipsoid ellipsoid){
		//创建GeodeticCalculator，调用计算方法，传入坐标系、经纬度用于计算距离
		GlobalCoordinates gpsFrom = new GlobalCoordinates(lat, lon);
		GlobalCoordinates gpsTo = new GlobalCoordinates(lat1, lon1);
		GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);
		return geoCurve.getEllipsoidalDistance();
	}

	/**
	 *   double
	 * @param lat
	 * @param lon
	 * @param lat1
	 * @param lon1
	 * @return
	 */
	public double getDistanceMeter(Double lat, Double lon,Double lat1, Double lon1){
		return getDistanceMeter(lat,lon,lat1,lon1, Ellipsoid.Sphere);
	}
	public double getDistanceMeter4WGS84(Double lat, Double lon,Double lat1, Double lon1){
		return getDistanceMeter(lat,lon,lat1,lon1, Ellipsoid.WGS84);
	}

	/**
	 * 转换成long
	 * @param lat
	 * @param lon
	 * @param lat1
	 * @param lon1
	 * @return
	 */
	public Long getDistanceMeter2Long(Double lat, Double lon,Double lat1, Double lon1){
		return (long) getDistanceMeter(lat,lon,lat1,lon1);
	}


	/**
	 * 传入通用对象判断距离
	 * @param from
	 * @param to
	 * @return
	 */
	public  Long getDistanceMeter2Long(Object from, Object to){
		Map fMap = toMap(from);
		Map tMap = toMap(to);
		return (long) getDistanceMeter(MapUtil.getDouble(fMap,latitude),MapUtil.getDouble(fMap,longitude)
				,MapUtil.getDouble(tMap,latitude),MapUtil.getDouble(tMap,longitude));
	}

	public Map toMap(Object o){
		Map map = BeanUtil.beanToMap(o);
		if (!(map.containsKey(latitude)&&map.containsKey(longitude))){
			throw new RuntimeException("经纬度字段不存在");
		}
		if (MapUtil.getDouble(map,latitude)==null||(MapUtil.getDouble(map,longitude)==null)){
			throw new RuntimeException("经纬度字段为空");
		}
		return map;
	}
}
